var app = getApp();
const pageName = 'packageG/independent_store/index/index';
Component({
  properties: {
    datas: {
      type: null
    },
    isDiy: {
      type: null
    },
    foot_type: {
      type: null
    }
  },
  // 私有数据，可用于模板渲染
  data: {
    activeSunIndex: '-1',//当前点击的一级菜单，用于处理子菜单显示
    // 默认数据
    defaultData: {
      "group_title": {
        "title": "底部导航名称",
        "type": "text",
        "value": "默认"
      },
      "button_item": {
        "title": "",
        "type": "bottomItem",
        "choose": "2",
        "menu_button": [{
          "id": 0,
          "text": "首页",
          "image": "",
          "icon": "icon-fontclass-shouye",
          "isIcon": "1",
          "link": "/packageG/index/index",
          "isMinApp": "1",
          "gh_id": "",
          "minApp_link": "",
          "sub_button": [],
          "isDefault": true,
        }, {
          "id": 1,
          "text": "分类",
          "image": "",
          "icon": "icon-fontclass-fenlei",
          "isIcon": "1",
          "link": "/packageG/pages/category_v2/category_v2",
          "isMinApp": "1",
          "gh_id": "",
          "minApp_link": "",
          "sub_button": [],
          "isDefault": true,
        }, {
          "id": 2,
          "text": "推广",
          "image": "",
          "icon": "icon-fontclass-tuiguang1",
          "isIcon": "1",
          "link": "/packageG/pages/member/extension/extension",
          "isMinApp": "1",
          "gh_id": "",
          "minApp_link": "",
          "sub_button": [],
          "isDefault": true,
        }, {
          "id": 3,
          "text": "购物车",
          "image": "",
          "icon": "icon-fontclass-gouwuche1",
          "isIcon": "1",
          "link": "/packageG/pages/buy/cart_v2/cart_v2",
          "isMinApp": "1",
          "gh_id": "",
          "minApp_link": "",
          "sub_button": [],
          "isDefault": true,
        }, {
          "id": 4,
          "text": "会员",
          "image": "",
          "icon": "icon-fontclass-huiyuanzhongxin",
          "isIcon": "1",
          "link": "/packageG/member_v2/member_v2",
          "isMinApp": "1",
          "gh_id": "",
          "minApp_link": "",
          "sub_button": [],
          "isDefault": true,
        }],
        "value": {}
      },
      "tab_style": {
        "title": "",
        "type": "tab",
        "value": {
          "text_set": {
            "text_show": true,
            "text_color": "#333333",
            "text_choose_color": "#ff4949"
          },
          "icon_set": {
            "icon_show": true,
            "icon_position": "top",
            "icon_color": "#333333",
            "icon_choose_color": "#ff4949"
          },
          "border_set": {
            "border_show": false,
            "border_color": "#e7e7eb",
            "border_choose_color": "#29ba9c"
          },
          "bg_set": {
            "bg_color": "#ffffff",
            "bg_choose_color": "#ffffff"
          },
          "children_set": {
            "children_color": "#333333",
            "children_choose_color": "#29ba9c",
            "children_bg_color": "#ffffff"
          }
        }
      }
    },
    // 门店独立模块数据
    storeData: {
      "group_title": {
        "title": "底部导航名称",
        "type": "text",
        "value": "默认"
      },
      "button_item": {
        "title": "",
        "type": "bottomItem",
        "choose": "2",
        "menu_button": [{
          "id": 0,
          "text": "首页",
          "image": "",
          "icon": "icon-ht_basis_shops",
          "isIcon": "1",
          "link": "/packageG/independent_store/index/index",
          "isMinApp": "1",
          "gh_id": "",
          "minApp_link": "",
          "sub_button": [],
          "isDefault": true,
        }, {
          "id": 1,
          "text": "商品",
          "size": "23",
          "image": "",
          "icon": "icon-ht_basis_goodgroup",
          "isIcon": "1",
          "link": "/packageC/o2o/o2oStore/o2oStore",
          "isMinApp": "1",
          "gh_id": "",
          "minApp_link": "",
          "sub_button": [],
          "isDefault": true,
        }, {
          "id": 2,
          "text": "买单",
          "size": "26",
          "image": "",
          "icon": "icon-shouyintai",
          "isIcon": "1",
          "link": "/packageC/cashier/cashier_pay/cashier_pay",
          "isMinApp": "1",
          "gh_id": "",
          "minApp_link": "",
          "sub_button": [],
          "isDefault": true,
        }, {
          "id": 3,
          "text": "会员",
          "image": "",
          "icon": "icon-fontclass-huiyuanzhongxin",
          "isIcon": "1",
          "link": "/packageG/member_v2/member_v2",
          "isMinApp": "1",
          "gh_id": "",
          "minApp_link": "",
          "sub_button": [],
          "isDefault": true,
        }],
        "value": {}
      },
      "tab_style": {
        "title": "",
        "type": "tab",
        "value": {
          "text_set": {
            "text_show": true,
            "text_color": "#333333",
            "text_choose_color": "#ff4949"
          },
          "icon_set": {
            "icon_show": true,
            "icon_position": "top",
            "icon_color": "#333333",
            "icon_choose_color": "#ff4949"
          },
          "border_set": {
            "border_show": false,
            "border_color": "#e7e7eb",
            "border_choose_color": "#29ba9c"
          },
          "bg_set": {
            "bg_color": "#ffffff",
            "bg_choose_color": "#ffffff"
          },
          "children_set": {
            "children_color": "#333333",
            "children_choose_color": "#29ba9c",
            "children_bg_color": "#ffffff"
          }
        }
      }
    },
    iPnoneBottomBol: false,
    emptyImage: '',
    menu_button: [],
    tab_style: {},
    seletedId: '', //当前选中菜单id
    selectedMenuIndex: "", //当前选中菜单索引
    selectedSubMenuIndex: "", //当前选中子菜单索引
    clientWidth: '375',

    routeData: '',
    temp: {},
    routeDataShow: true,

    default_Id:"",
    cartNum: 0
  },

  lifetimes: {
    // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
    attached() {
      this.getiPnoneBottom();
      try {
        let info_basic = wx.getStorageSync('yz_basic_info');
        this.setData({
          basic_info : info_basic.plugin_setting.instation_message,
          cartNum: app.globalData.cart_num||info_basic.globalParameter.cart_num||0
        })
      } catch (error) {}

      let self = this;
      app.watchGlobalData('cart_num',self.watchCartNum.bind(self));//监听globalData.cart_num的变化，注意：回调方法后面要重新绑定this,否则回调里获取不到this
    },
    moved() {},
    detached() {},
  },

  // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
  attached() {},
  // 此处attached的声明会被lifetimes字段中的声明覆盖
  ready() {
    this.setData({
      // height: wx.getSystemInfoSync().windowHeight,
      clientWidth: wx.getSystemInfoSync().windowWidth,
    });
    let default_Id = wx.getStorageSync('default_Id');
    if(default_Id){
      this.setData({default_Id})
    }
  
    let pages = getCurrentPages(); //获取加载的页面
    let currentPage = pages[pages.length - 1]; //获取当前页面的对象
    // 页面路由 pageName：独立门店路由
    let pathName = currentPage.__route__;
    this.setData({
      routeData: currentPage.route,
      selectedMenuIndex: ''
    });

    let that = this;
    // console.log(this.data.datas,this.data.foot_type,"this.data.foot_type")
    // console.log(pathName , pageName, "pageName")
    //  首页或者装修页
    if (this.data.isDiy && this.data.datas) {
      // 使用装修但又是独立模块还是走独立模块的
      if (app.globalData.store_alone_temp == 1 || pathName == pageName) {
        // 门店独立模块
        that.setData({
        //   menu_button: that.data.storeData.button_item.menu_button,
          tab_style: that.data.storeData.tab_style.value
        });
        this.getStoreMenu();
        // 显示storeData的底部导航
        if (that.data.menu_button) {
          let menus = that.data.menu_button;
          for (let i = 0; i < menus.length; i++) {
            let url = menus[i].link;
            if (url.indexOf(that.data.routeData) >= 0 && menus[i].sub_button.length <= 0) {
              that.setData({
                routeDataShow: true,
                selectedMenuIndex: i,
              });
              break;
            }
          }
        }
        return
      }
      if (this.data.foot_type == -1) {
        // 不显示
        this.setData({
          routeDataShow: false,
        });
      } else if (!this.data.foot_type || this.data.foot_type == 1) {
        if (this.data.datas.group_title) {
          // 显示列表默认
          this.setData({
            menu_button: this.data.datas.button_item.menu_button,
            tab_style: this.data.datas.tab_style.value
          });
        } else {
          // 显示系统默认
          this.setData({
            menu_button: this.data.defaultData.button_item.menu_button,
            tab_style: this.data.defaultData.tab_style.value
          });
        }

        if (this.data.menu_button) {
          let menus = this.data.menu_button;
          for (let i = 0; i < menus.length; i++) {
            let url = menus[i].link;
            if (url.indexOf(that.data.routeData) >= 0) {
              if (that.data.routeData == 'packageG/newDiy/newDiy') {
                //diy页面加判断个id，来判断是否当前diy页面
                if (currentPage.options && url.indexOf(Number(currentPage.options.page_id)) >= 0) {
                  that.setData({
                    selectedMenuIndex: i,
                  });
                  break;
                }
              } else {
                that.setData({
                  selectedMenuIndex: i,
                });
                break;
              }
            }
          }

          // 二级用seletedId显示
          for (let k = 0; k < menus.length; k++) {
            for (let j = 0; j < menus[k].sub_button.length; j++) {
              let url_1 = menus[k].sub_button[j].link;
              if (url_1.indexOf(that.data.routeData) >= 0) {
                that.setData({
                  selectedSubMenuIndex: k,
                  // seletedId: menus[k].sub_button[j].id,
                });

                if(that.data.default_Id){
                  that.setData({
                    seletedId: that.data.default_Id
                  });
                }else{
                  that.setData({
                    seletedId: menus[k].sub_button[j].id,
                  });
                }
                

                break;
              }
            }
          }

        }

      } else if (this.data.foot_type == 2) {
        // 显示自定义的底部导航
        if (!this.data.datas.group_title) {
          this.setData({
            routeDataShow: false,
          });
          return;
        }

        this.setData({
          menu_button: this.data.datas.button_item.menu_button,
          tab_style: this.data.datas.tab_style.value
        });
        if (this.data.datas.button_item && this.data.datas.button_item.menu_button) {
          let menus = this.data.datas.button_item.menu_button;
          for (let i = 0; i < menus.length; i++) {
            let url = menus[i].link;
            if (url.indexOf(that.data.routeData) >= 0) {
              if (that.data.routeData == 'packageG/newDiy/newDiy') {
                //diy页面加判断个id，来判断是否当前diy页面
                if (currentPage.options && url.indexOf(Number(currentPage.options.page_id)) >= 0) {
                  that.setData({
                    selectedMenuIndex: i,
                  });
                  break;
                }
              } else {
                that.setData({
                  selectedMenuIndex: i,
                });
                break;
              }
            }
          }

          // 二级用seletedId显示
          for (let k = 0; k < menus.length; k++) {
            for (let j = 0; j < menus[k].sub_button.length; j++) {
              let url_1 = menus[k].sub_button[j].link;
              if (url_1.indexOf(that.data.routeData) >= 0) {
                that.setData({
                  selectedSubMenuIndex: k,
                  seletedId: menus[k].sub_button[j].id,
                });
                break;
              }
            }
          }

        }

      }

    } else if (app.globalData.store_alone_temp == 1 || pathName == pageName) {
      console.log(wx.getStorageSync('storeMenu'),'storeMenu')
      // 门店独立模块
      that.setData({
      //   menu_button: that.data.storeData.button_item.menu_button,
        tab_style: that.data.storeData.tab_style.value
      });
      this.getStoreMenu();

      // 显示storeData的底部导航
      if (that.data.menu_button) {
        let menus = that.data.menu_button;
        for (let i = 0; i < menus.length; i++) {
          let url = menus[i].link;
          if (url.indexOf(that.data.routeData) >= 0 && menus[i].sub_button.length <= 0) {
            that.setData({
              routeDataShow: true,
              selectedMenuIndex: i,
            });
            break;
          }
        }
      }

    } else {
      //  其他页面
      wx.getStorage({
        key: 'yz_basic_info',
        success(res) {
          if (res.data) {
            that.setData({
              temp: res.data.home
            });

            // let url = that.data.routeData;
            if (that.data.routeData.indexOf('o2oHome') >= 0 ||
              that.data.routeData.indexOf('VideoList') >= 0 || that.data.routeData.indexOf('easyRefuel') >= 0 ||
              that.data.routeData.indexOf('VideoDetail') >= 0 || that.data.routeData.indexOf('groupCode') >= 0 || that.data.routeData.indexOf('questionnaireIndex') >= 0 ||
              that.data.routeData.indexOf('groupCodeRanking') >= 0 || that.data.routeData.indexOf('groupCodeShow') >= 0 ||
              that.data.routeData.indexOf('groupCodeRecord') >= 0 || that.data.routeData.indexOf('groupCodeData') >= 0) {
              that.setData({
                routeDataShow: true
              });
            }

            if (that.data.iPnoneBottomBol) {
              that.triggerEvent("showcarrfoot_ipx", true);
            } else {
              that.triggerEvent("showcarrfoot", true);
            }

            if (that.data.temp.item.menus && that.data.temp.item.menus.page_info) {
              // 显示列表默认
              let menu = JSON.parse(that.data.temp.item.menus.page_info);
              that.setData({
                menu_button: menu.button_item.menu_button,
                tab_style: menu.tab_style.value
              });
            } else {
              // 显示系统默认
              that.setData({
                menu_button: that.data.defaultData.button_item.menu_button,
                tab_style: that.data.defaultData.tab_style.value
              });
            }

            // 显示自定义的底部导航
            if (that.data.menu_button) {
              let menus = that.data.menu_button;
              for (let i = 0; i < menus.length; i++) {
                let url = menus[i].link;
                if (url.indexOf(that.data.routeData) >= 0 && menus[i].sub_button.length <= 0) {
                  if (that.data.routeData == 'packageG/newDiy/newDiy') {
                    //diy页面加判断个id，来判断是否当前diy页面
                    if (currentPage.options && url.indexOf(Number(currentPage.options.page_id)) >= 0) {
                      that.setData({
                        routeDataShow: true,
                        selectedMenuIndex: i,
                      });
                      break;
                    }
                  } else {
                    that.setData({
                      routeDataShow: true,
                      selectedMenuIndex: i,
                    });
                    break;
                  }

                }
              }

              // 二级用seletedId显示
              for (let k = 0; k < menus.length; k++) {
                for (let j = 0; j < menus[k].sub_button.length; j++) {
                  let url_1 = menus[k].sub_button[j].link;
                  if (url_1.indexOf(that.data.routeData) >= 0) {
                    that.setData({
                      routeDataShow: true,
                      selectedSubMenuIndex: k,
                      seletedId: menus[k].sub_button[j].id,
                    });
                    break;
                  }
                }
              }
            }

          }
        },
        fail() {
          that.getTemp();
        }
      });
    }
  },

  pageLifetimes: {
    // 组件所在页面的生命周期函数
    show() {},
    hide() {},
    resize() {},
  },

  methods: {
    getStoreMenu(){
      var urlStr = app.getNetAddresss("plugin.store-alone-temp.frontend.home.get-set-nav-data");
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            console.log(res.data)
            wx.setStorageSync('storeMenu',res.data)
            this.setData({
              menu_button: res.data,
            });
          }
        },
        fail: function (res) {

        }
      });
    },
    getTemp() {
      // 缓存获取不到请求接口
      var that = this;
      var urlStr = app.getNetAddresss("home-page.wxapp");
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              temp: res.data
            });

            // let url = that.data.routeData;
            if (that.data.routeData.indexOf('o2oHome') >= 0 ||
              that.data.routeData.indexOf('VideoList') >= 0 || that.data.routeData.indexOf('easyRefuel') >= 0 ||
              that.data.routeData.indexOf('VideoDetail') >= 0 || that.data.routeData.indexOf('groupCode') >= 0 || that.data.routeData.indexOf('questionnaireIndex') >= 0 ||
              that.data.routeData.indexOf('groupCodeRanking') >= 0 || that.data.routeData.indexOf('groupCodeShow') >= 0 ||
              that.data.routeData.indexOf('groupCodeRecord') >= 0 || that.data.routeData.indexOf('groupCodeData') >= 0) {
              that.setData({
                routeDataShow: true
              });
            }

            if (that.data.iPnoneBottomBol) {
              that.triggerEvent("showcarrfoot_ipx", true);
            } else {
              that.triggerEvent("showcarrfoot", true);
            }

            if (that.data.temp.item.foot && that.data.temp.item.foot.page_info) {
              // 显示列表默认
              let menu = JSON.parse(that.data.temp.item.foot.page_info);
              that.setData({
                menu_button: menu.button_item.menu_button,
                tab_style: menu.tab_style.value
              });
            } else {
              // 显示系统默认
              that.setData({
                menu_button: that.data.defaultData.button_item.menu_button,
                tab_style: that.data.defaultData.tab_style.value
              });
            }

            // 显示自定义的底部导航
            if (that.data.menu_button) {
              let menus = that.data.menu_button;
              for (let i = 0; i < menus.length; i++) {
                let url = menus[i].link;
                if (url.indexOf(that.data.routeData) >= 0 && menus[i].sub_button.length <= 0) {
                  if (that.data.routeData == 'packageG/newDiy/newDiy') {
                    //diy页面加判断个id，来判断是否当前diy页面
                    if (currentPage.options && url.indexOf(Number(currentPage.options.page_id)) >= 0) {
                      that.setData({
                        routeDataShow: true,
                        selectedMenuIndex: i,
                      });
                      break;
                    }
                  } else {
                    that.setData({
                      routeDataShow: true,
                      selectedMenuIndex: i,
                    });
                    break;
                  }

                }
              }

              // 二级用seletedId显示
              for (let k = 0; k < menus.length; k++) {
                for (let j = 0; j < menus[k].sub_button.length; j++) {
                  let url_1 = menus[k].sub_button[j].link;
                  if (url_1.indexOf(that.data.routeData) >= 0) {
                    that.setData({
                      routeDataShow: true,
                      selectedSubMenuIndex: k,
                      seletedId: menus[k].sub_button[j].id,
                    });
                    break;
                  }
                }
              }
            }

          }
        },
        fail: function (res) {

        }
      });
    },
    /**
     * 处理数据
     * @param {String} datas
     * **/
    handle_data(datas) {
      let handleDatas = {};
      Object.keys(datas).map(key => {
        handleDatas[key] = datas[key].value;
      });
      return handleDatas;
    },
    //选中主菜单
    selectedMenu(e) {
      let item = e.currentTarget.dataset.item;
      let index = e.currentTarget.dataset.index;
      
      if ((this.data.selectedMenuIndex !== index && item.sub_button.length == 0)) {
        this.setData({
          selectedSubMenuIndex: "",
          selectedMenuIndex: index,
        });
      } else if(item.sub_button.length > 0){
        this.setData({
          activeSunIndex: this.data.activeSunIndex == index?-1:index
        });      
        // this.setData({
        //   selectedSubMenuIndex: "",
        //   selectedMenuIndex: "",
        // });
        // return;
      } else if (this.data.activeSunIndex == index && item.sub_button.length > 0){
        this.setData({
          activeSunIndex: '-1'
        });
        
      }

      if (item.sub_button.length == 0) {
        if (item.isMinApp == 2) {
          if (item.gh_id) {
            if (item.minApp_link) {
              try {
                wx.navigateToMiniProgram({
                  appId: item.gh_id,
                  path: item.minApp_link,
                  extraData: {},
                  envVersion: 'release',
                  success(res) {
                    // 打开成功
                  },
                  fail(res) {
                    wx.showToast({
                      title: '小程序跳转失败',
                      icon: 'none',
                      duration: 2000
                    });
                  }
                });
              } catch (e) {
                wx.showToast({
                  title: '小程序跳转失败',
                  icon: 'none',
                  duration: 2000
                });
              }
            } else {
              wx.showToast({
                title: '请设置跳转小程序后的跳转链接',
                icon: 'none',
                duration: 2000
              });
            }
          } else {
            wx.showToast({
              title: '请设置小程序所需跳转appId',
              icon: 'none',
              duration: 2000
            });
          }
        } else {
          if (item.link === this.data.routeData) {
            return;
          }
          let url = item.link;

          if (app.globalData.store_alone_temp == 1) {
            // 门店独立模块底部导航
            url += `?store_id=${app.globalData.STORE_ID}`;
          }

          if (url) {
            try {
              if (app.globalData.store_alone_temp == 1 && (item.id == 1 || item.id == 2)) {
                wx.navigateTo({
                  url: url
                });
              } else {
                wx.redirectTo({
                  url: url,
                  fail: () => {
                    app.tips('链接设置错误:' + url);
                  }
                });
              }
            } catch (e) {
              app.tips('链接设置错误:' + url);
            }
          } else {
            app.tips('请设置跳转链接');
          }
        }
      }

    },
    //选中子菜单
    selectedSubMenu(e) {
      let index = e.currentTarget.dataset.index;
      let item = e.currentTarget.dataset.item;

      if (item.isMinApp == 2) {
        if (item.gh_id) {
          if (item.minApp_link) {
            try {
              wx.navigateToMiniProgram({
                appId: item.gh_id,
                path: item.minApp_link,
                extraData: {},
                envVersion: 'release',
                success(res) {
                  // 打开成功
                },
                fail(res) {
                  wx.showToast({
                    title: '小程序跳转失败',
                    icon: 'none',
                    duration: 2000
                  });
                }
              });
            } catch (e) {
              wx.showToast({
                title: '小程序跳转失败',
                icon: 'none',
                duration: 2000
              });
            }
          } else {
            wx.showToast({
              title: '请设置跳转小程序后的跳转链接',
              icon: 'none',
              duration: 2000
            });
          }
        } else {
          wx.showToast({
            title: '请设置小程序所需跳转appId',
            icon: 'none',
            duration: 2000
          });
        }
      } else {
        if (item.link === this.data.routeData) {
          return;
        }
        let url = item.link;
        this.setData({
          selectedSubMenuIndex: index,
        });
        let selectedSubMenu = this.data.menu_button[this.data.activeSunIndex].sub_button[this.data.selectedSubMenuIndex];
        this.setData({
          seletedId: selectedSubMenu.id,
          default_Id:selectedSubMenu.id
        });

        wx.setStorageSync('default_Id', this.data.default_Id)

        if (url) {
          try {
            wx.redirectTo({
              url: url,
              fail: () => {
                app.tips('链接设置错误:' + url);
              }
            });
          } catch (e) {
            wx.showToast({
              title: '链接设置错误:' + url,
              icon: 'none',
              duration: 2000
            });
          }
        } else {
          wx.showToast({
            title: '请设置跳转链接',
            icon: 'none',
            duration: 2000
          });
        }
      }
    },
    getiPnoneBottom() {
      let that = this;
      try {
        var value = wx.getStorageSync('iPhoneBottom');
        if (value) {
          that.setData({
            iPnoneBottomBol: true
          });
          // Do something with return value
        }
      } catch (e) {
        // Do something when catch error
      }
    },
    goindex() {
      wx.redirectTo({
        url: '/packageG/index/index'
      });
    },
    gocategory() {
      wx.redirectTo({
        url: '/packageG/pages/category_v2/category_v2'
      });
    },
    goextension() {
      wx.redirectTo({
        url: '/packageG/pages/member/extension/extension'
      });
    },
    gocart() {
      wx.redirectTo({
        url: '/packageG/pages/buy/cart_v2/cart_v2'
      });
    },
    gomember() {
      wx.redirectTo({
        url: '/packageG/member_v2/member_v2'
      });
    },
    watchCartNum(value){
      this.setData({
        cartNum: value
      })
    }
  }
});
